<script setup lang="ts">
import { Slicer } from '@/models/reactiveComponent';
import { computed, ref, watch, inject } from 'vue'
import * as cpUtils from './utils';
import Error from "./Error.vue";
import * as injectKeys from "@/services/injectKeys";
import { valuesArray2sqlArray } from '@/services/dbServices';


const props = defineProps<{ model: Slicer }>()
const model = props.model

const datasetServices = inject(injectKeys.datasetKey)!
const sqlServices = inject(injectKeys.sqlAnalyzeKey)!
const dbServices = inject(injectKeys.dbKey)!


const filterUtils = cpUtils.getFilterUtils(model, {
    dataset: datasetServices,
    sqlAnalyze: sqlServices,
    db: dbServices,
})

const data = filterUtils.getData()

let sqlPropName = null as unknown as string

const options = computed(() => {

    if (data.value.rows.length > 0) {
        const rows = data.value.rows

        if (!sqlPropName) {
            sqlPropName = data.value.fields[0]
        }

        return rows.map(r => {
            return {
                label: r[sqlPropName]!.toString(),
                value: r[sqlPropName]!.toString(),
            }
        })
    }

    return []

})



const selecteds = ref<any[] | any>()
watch(selecteds, values => {

    if (!Array.isArray(values)) {
        values = [values]
    }

    if (values.length === 0) {
        filterUtils.removeFilter()
    } else {
        const sql = valuesArray2sqlArray(values).join(',')

        filterUtils.addFilter(`in (${sql})`)
    }
})

</script>

<template>
    <div class="slicer-box" :data-tag="model.tag">
        <label class="title">{{ props.model.title }}</label>

        <Error>
            <el-select :multiple="props.model.multiple" filterable clearable collapse-tags collapse-tags-tooltip
                v-model="selecteds" class="m-2" placeholder="Select">
                <el-option v-for="item in options" :key="item.label" :label="item.label" :value="item.value" />
            </el-select>

        </Error>

    </div>
</template>

<style scoped>
.slicer-box {
    /* display: inline-block; */
    min-width: 8rem;
    margin-right: 0.8rem;
}

.title {
    display: block;
    margin-bottom: 0.5rem;
}
</style>